package com.zjz.studynotes;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.widget.Button;
import android.widget.EditText;

import androidx.activity.ComponentActivity;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.zjz.studynotes.bean.StudyNoteInfo;
import com.zjz.studynotes.db.StudyNotesDb;

import java.util.ArrayList;
import java.util.List;

/**
 * Description: 主页
 * Author: zjz
 * Date:2025/5/5 13:06
 */
public class MainActivity extends ComponentActivity {
    private EditText mEtSearch;
    private RecyclerView mRvList;
    private Button mBtnAdd;

    private StudyNotesAdapter mAdapter;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mEtSearch = findViewById(R.id.et_search);
        mRvList = findViewById(R.id.rv_list);
        mBtnAdd = findViewById(R.id.btn_add);

        mBtnAdd.setOnClickListener(view -> go2Edit());

        mEtSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (TextUtils.isEmpty(editable.toString())) {
                    initData();
                } else {
                    //模糊搜索
                    List<StudyNoteInfo> list = StudyNotesDb.getInstance(MainActivity.this).getStudyNoteInfoDao().queryInfoByKey("%"+editable.toString()+"%");
                    data.clear();
                    data.addAll(list);
                    mAdapter.notifyDataSetChanged();
                }
            }
        });

        initList();
    }

    private void go2Edit() {
        //跳转到新增笔记页面
        startActivity(new Intent(this, AddActivity.class));
    }

    private List<StudyNoteInfo> data = new ArrayList<>();
    private void initList() {

        mAdapter = new StudyNotesAdapter(this,data);

        mRvList.setAdapter(mAdapter);
        mRvList.setLayoutManager(new LinearLayoutManager(this));
    }


    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    private void initData() {
        //初始化数据，刷新页面
        List<StudyNoteInfo> list = StudyNotesDb.getInstance(this).getStudyNoteInfoDao().queryAll();
        data.clear();
        data.addAll(list);
        mAdapter.notifyDataSetChanged();
    }
}
